//
//  GMUserInfoViewController.m
//  BeautyFace
//
//  Created by steven on 2017/1/3.
//  Copyright © 2017年 steven. All rights reserved.
//

#import "GMUserInfoViewController.h"
#import "GMUserInfoDataController.h"
#import "GMUserNameViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>

#define kUserInfoTableViewCellIdentifier @"kUserInfoTableViewCellIdentifier"

@interface GMUserInfoViewController ()<UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong)GMUserInfoDataController *userInfoDataController;

@end

@implementation GMUserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.userInfoDataController = [[GMUserInfoDataController alloc] init];
    [self setupContentView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

#pragma mark - set up content view
- (void)setupContentView {
    self.navigationItem.title = @"个人信息";
    [self.view addSubview:self.tableView];
    [self.tableView autoPinEdgesToSuperviewEdges];
}

#pragma mark - Getter for tableview
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = UIColorFromRGB(0xF8F4F4);
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    
    return _tableView;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kUserInfoTableViewCellIdentifier];
    }
    
    if (indexPath.row == 0) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        NSString *headImageUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"headImageUrl"];
        UIImageView *headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
        headImageView.layer.cornerRadius = 40;
        headImageView.layer.masksToBounds = YES;
        [headImageView sd_setImageWithURL:[NSURL URLWithString:headImageUrl] placeholderImage:[UIImage imageNamed:@"default-user-icon"]];
        cell.textLabel.text = @"头像";
        cell.accessoryView = headImageView;
    } else {
        NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"name"];
        cell.textLabel.text = @"昵称";
        cell.detailTextLabel.text = name;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 100;
    } else {
        return 44;
    }
}

#pragma mark - UITableViewDatasource
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        __weak typeof(self)weakSelf = self;
        // show action sheet for camera and photo selection
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"选择头像" message:@"从以下方式中选择图片" preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // show image picker
            NSLog(@"select image picker");
            __strong typeof(weakSelf)strongSelf = weakSelf;
            // Popup ImagePicker
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.navigationBar.tintColor = [UIColor blackColor];
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePickerController.delegate = strongSelf;
            imagePickerController.allowsEditing = YES;
            [strongSelf presentViewController:imagePickerController animated:YES completion:nil];
        }];
        [alertController addAction:photoAction];
        
        UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // show camera
            NSLog(@"select camera");
            __strong typeof(weakSelf)strongSelf = weakSelf;
            // Popup ImagePicker
            UIImagePickerController *cameraPickerController = [[UIImagePickerController alloc] init];
            cameraPickerController.navigationBar.tintColor = [UIColor blackColor];
            cameraPickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            cameraPickerController.delegate = strongSelf;
            cameraPickerController.allowsEditing = YES;
            [strongSelf presentViewController:cameraPickerController animated:YES completion:nil];
        }];
        [alertController addAction:cameraAction];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
    } else {
        GMUserNameViewController *userNameViewController = [[GMUserNameViewController alloc] init];
        [self.navigationController pushViewController:userNameViewController animated:YES];
    }
}

#pragma mark - UIImageViewControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    
    [self.userInfoDataController uploadAvatarWithImage:imageData params:nil callback:^(NSString *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error == nil) {
                [self showSuccessView];
            } else {
                [self showAlertMessage:error];
            }
        });
    }];

}

#pragma mark - success view
- (void)showSuccessView {
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
